import fs from 'fs';
import { Logger } from '../utils/logger.js';
import { fileURLToPath } from 'url';
import config from '../utils/config.js';
import { execAsync } from '../utils/exec.js';

const logger = new Logger('[config:sync]');

async function syncToPackageJson() {
  // 加载 YAML
  logger.info(`📄 加载 YAML: ${config.yamlPath}`);
  const scripts = config.yamlConfig;

  // 加载 package.json
  const packageJson = config.packageJson;

  // 构建新的 scripts 对象
  const newScripts = {};
  Object.entries(scripts).forEach(([name, info]) => {
    // 处理 YAML 键名中的冒号
    const scriptName = name.replace(/:/g, ':');
    newScripts[scriptName] = info.command;
  });

  // 保留原有的但不在 YAML 中的脚本（可选）
  const preserve = ['test', 'lint', 'format', 'prepare']; // 要保留的脚本
  preserve.forEach((key) => {
    if (packageJson.scripts[key] && !newScripts[key]) {
      newScripts[key] = packageJson.scripts[key];
    }
  });

  // 更新 package.json
  packageJson.scripts = newScripts;

  // 写回文件
  logger.info(`📝 写入 : ${config.packagePath}`);
  await fs.writeFileSync(config.packagePath, JSON.stringify(packageJson, null, 2) + '\n');

  // 尝试 prettier 格式化 package.json
  try {
    logger.info('🔄 prettier 格式化');
    await execAsync('pnpm', ['prettier', '-w', config.packagePath], {
      shell: true,
      silent: true,
    });
  } catch (error) {
    logger.warning('prettier 格式化 package.json 失败: ' + error.message);
  }

  logger.success('同步完成！');
  logger.info(`📝 已更新 ${Object.keys(newScripts).length} 个脚本到 package.json`);

  // 显示变更
  const oldKeys = new Set(Object.keys(packageJson.scripts || {}));
  const newKeys = new Set(Object.keys(newScripts));

  const added = [...newKeys].filter((k) => !oldKeys.has(k));
  const removed = [...oldKeys].filter((k) => !newKeys.has(k));

  if (added.length > 0) {
    logger.info('✨ 新增的脚本:');
    added.forEach((k) => console.log(`  + ${k}`));
  }

  if (removed.length > 0) {
    logger.info('🗑️  移除的脚本:');
    removed.forEach((k) => console.log(`  - ${k}`));
  }
}

// 执行
const __filename = fileURLToPath(import.meta.url);
const isMain = process.argv[1] === __filename;

if (isMain) {
  syncToPackageJson();
}

export { syncToPackageJson };
